package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.mapper.SysTenantMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysTenantService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;

@Service
@Slf4j
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysUserService sysUserService;



    /**
     * 保存用户租户和帐号数据
     * @param sysTenant 租户实体
     * @return
     */
    @Override
    @Transactional
    public void saveSysTenant(SysTenant sysTenant){
        //保存租户信息
        save(sysTenant);
        //保存账号信息
        SysUser sysUser = new SysUser();
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        sysUser.setUsername(sysTenant.getUsername());
        String passwordEncode = PasswordUtil.encrypt(sysTenant.getUsername(), sysTenant.getPassword(), salt);
        sysUser.setPassword(passwordEncode);
        sysUser.setStatus(1);
        sysUser.setDelFlag(CommonConstant.DEL_FLAG_0);
        sysUser.setCreateTime(new Date());
        sysUser.setTenantId(sysTenant.getId() + "");
        sysUserService.save(sysUser);
        SysUserRole userRole = new SysUserRole(sysUser.getId(), "1424637617896579073");
        sysUserRoleMapper.insert(userRole);
    }
}
